package priv.yiyuan.example.design.facade;

/**
 * 订单处理类
 * <p>
 * 外观模式-外观类
 * 单例模式
 *
 * @author YiYuan
 * @data 2025/9/12
 * @apoNote
 */
public class OrderProcessingFacade {

    private static OrderProcessingFacade instance;

    private InventoryService inventoryService;

    private PaymentService paymentService;

    private NotificationService notificationService;

    private OrderProcessingFacade() {
        inventoryService = new InventoryService();
        paymentService = new PaymentService();
        notificationService = new NotificationService();
    }

    public static synchronized OrderProcessingFacade getInstance() {
        if (instance == null) {
            instance = new OrderProcessingFacade();
        }

        return instance;
    }

    public boolean placeOrder(String productId, int quantity, String userEmail, double amount) {

        System.out.println("\n--- 订单处理: 开始处理订单 ---");

        String orderId = "ORDER_" + System.currentTimeMillis();

        inventoryService.deductStock(productId, quantity);

        boolean paymentSuccess = paymentService.makePayment(orderId, amount);

        if (paymentSuccess) {
            notificationService.sendOrderConfirmation(orderId, userEmail);
            System.out.println("\n--- 订单处理: 订单处理成功 ---");
            return true;
        }
        else {
            inventoryService.restoreStock(productId, quantity);
            notificationService.sendPaymentFailedNotification(orderId, userEmail);
            System.out.println("\n--- 订单处理: 订单处理失败 ---");
            return false;
        }

    }
}
